<template>
  <div :key="$route.params.id">
    <div class="post-detail-page">
      <!-- 添加返回按钮 -->
      <div class="page-header" v-if="notFound">
        <button class="back-btn" @click="$router.push('/forum')">
          <i class="el-icon-arrow-left"></i>
          返回论坛
        </button>
      </div>

      <!-- 添加加载状态 -->
      <div v-if="loading" class="loading-wrapper">
        <el-loading :fullscreen="true"></el-loading>
      </div>

      <!-- 添加错误提示 -->
      <div v-else-if="error" class="error-wrapper">
        <p>{{ error }}</p>
        <el-button type="primary" @click="fetchPostDetail($route.params.id)">重试</el-button>
      </div>

      <!-- 帖子内容 -->
      <div v-else-if="post" class="detail-container">
        <div class="detail-card">
          <h1 class="post-title">{{ post.title }}</h1>
          <div class="post-meta">
            <span class="author">用户{{ post.userId }}</span>
            <span class="time">{{ formatTime(post.createTime) }}</span>
          </div>
          <div class="post-content">{{ post.content }}</div>
          
          <div v-if="post.images" class="post-image">
            <img :src="post.images" :alt="post.title" />
          </div>

          <div class="post-stats">
            <span><i class="el-icon-view"></i> {{ post.views || 0 }}</span>
            <span><i class="el-icon-chat-dot-round"></i> {{ post.comments || 0 }}</span>
            <span><i class="el-icon-star-off"></i> {{ post.likes || 0 }}</span>
          </div>
        </div>

        <!-- 点赞和收藏按钮 -->
        <div class="actions">
          <button @click="toggleLike">{{ isLiked ? '取消点赞' : '点赞' }} </button>
          <button @click="favoritePost">收藏</button>
        </div>

        <!-- 评论区 -->
        <div class="comments">
          <h3>评论</h3>
          <div v-for="comment in postDetail.comments || []" :key="comment.id" class="comment">
            <p><strong>{{ comment.authorName }}:</strong> {{ comment.content }}</p>
          </div>
          <textarea v-model="newComment" placeholder="写下你的评论..."></textarea>
          <button @click="submitComment">提交评论</button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-wrapper">
        <p>帖子不存在或已被删除</p>
        <el-button type="primary" @click="$router.push('/forum')">返回列表</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'PostDetail',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      notFound:false,
      post: null,
      loading: false,
      error: null,
      commentText: '',
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      postDetail: {},
      postId: null,
      newComment: '',
      isLiked: false
    }
  },
  created() {
    console.log('详情页面创建，路由参数:', this.$route.params)
    this.postId = this.$route.params.id
    this.fetchPostDetail()
  },
  methods: {
    async fetchPostDetail() {
      console.log('开始获取帖子详情，ID:', this.postId)
      try {
        const response = await axios.get(`/api/posts/${this.postId}`)
        console.log('获取到帖子数据:', response.data)
        if (response.data.code === 200) {
          this.post = response.data.data
          if(this.post!=null){
            this.notFound=false
          }else{
            this.notFound=true
          }
          this.postDetail = response.data.data;
          const currentUserId = localStorage.getItem('userId');
          this.isLiked = this.postDetail.likeList.includes(currentUserId);
        }
      } catch (error) {
        // console.error('获取帖子详情失败:', error)
        // this.$message.error('获取帖子详情失败')
      }
    },
    formatTime(time) {
      return new Date(time).toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    async submitComment() {
      if (!this.newComment) return;
      try {
        await axios.post(`/api/posts/${this.postId}/comments`, {
          content: this.newComment
        });
        this.postDetail.comments.push({
          authorName: '当前用户', // 假设当前用户信息
          content: this.newComment
        });
        this.newComment = ''; // 清空评论框
      } catch (error) {
        console.error('Error submitting comment:', error);
      }
    },
    async likePost() {
      try {
        await axios.post(`/api/posts/${this.postId}/like`);
        this.postDetail.likes += 1; // 更新点赞数
      } catch (error) {
        console.error('Error liking post:', error);
      }
    },
    async favoritePost() {
      try {
        await axios.post(`/api/posts/${this.postId}/favorite`);
        console.log('Post favorited successfully');
      } catch (error) {
        console.error('Error favoriting post:', error);
      }
    },
    async toggleLike() {
      try {
        if (this.isLiked) {
          await axios.post(`/api/posts/${this.postId}/unlike`);
          this.postDetail.likes -= 1;
        } else {
          await axios.post(`/api/posts/${this.postId}/like`);
          this.postDetail.likes += 1;
        }
        this.isLiked = !this.isLiked;
      } catch (error) {
        console.error('Error toggling like:', error);
      }
    },
    async unlikePost() {
      try {
        await axios.delete(`/api/posts/${this.postId}/like`);
        this.postDetail.likes -= 1; // 更新点赞数
      } catch (error) {
        console.error('Error unliking post:', error);
      }
    }
  },
  // 添加路由参数变化的监听
  // watch: {
  //   id: {
  //     immediate: true,
  //     handler(newId) {
  //       this.fetchPostDetail(newId)
  //     }
  //   }
  // },
  // beforeRouteUpdate(to, from, next) {
  //   // 路由更新时重新获取数据
  //   this.postId = to.params.id;
  //   this.fetchPostDetail();
  //   next();
  // }
}
</script>

<style scoped>
.post-detail-page {
  min-height: 100vh;
  background: #f6f7f9;
  padding: 20px;
}

/* 添加返回按钮样式 */
.page-header {
  max-width: 800px;
  margin: 0 auto 20px;
  padding: 0 20px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  background: white;
  border-radius: 8px;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  background: #f0f2f5;
  color: #1890ff;
}

.detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.detail-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.post-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.post-meta {
  color: #666;
  margin-bottom: 20px;
}

.post-meta > span {
  margin-right: 16px;
}

.post-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  margin-bottom: 24px;
}

.post-image {
  margin: 24px 0;
  border-radius: 8px;
  overflow: hidden;
}

.post-image img {
  width: 100%;
  max-height: 500px;
  object-fit: contain;
}

.post-stats {
  display: flex;
  gap: 24px;
  color: #666;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.loading-wrapper,
.error-wrapper,
.empty-wrapper {
  text-align: center;
  padding: 40px;
  color: #666;
}

.actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

button {
  padding: 8px 16px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #0056b3;
}

.comments {
  margin-top: 30px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.comment {
  margin-bottom: 15px;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

textarea {
  width: 100%;
  height: 80px;
  margin-top: 10px;
  padding: 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
  resize: none;
}

textarea:focus {
  border-color: #007bff;
  outline: none;
}
</style> 